package api

import (
	"spam3uk/internal/storage"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// SetupRoutes 设置路由
func SetupRoutes(storage storage.VehicleStorage, logger *logrus.Logger, version string) *gin.Engine {
	// 设置Gin模式
	gin.SetMode(gin.ReleaseMode)

	// 创建Gin实例
	router := gin.New()

	// 添加中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())
	router.Use(CORSMiddleware())

    // 创建处理器
    vehicleHandler := NewVehicleHandler(storage, logger, version)

	// API路由组
	api := router.Group("/api")
	{
		api.GET("/get_all_cars", vehicleHandler.GetAllCars)
		api.GET("/vehicles", vehicleHandler.GetAllCars) // 新的推荐端点
		api.GET("/cars/:id", vehicleHandler.GetCarByID)
		api.GET("/categories", vehicleHandler.GetFordCategories)
		api.GET("/categories/:category/vehicles", vehicleHandler.GetVehiclesByCategory)
		api.GET("/get_trims", vehicleHandler.GetTrims)        // 新的trim端点
		api.POST("/scrape_trims", vehicleHandler.ScrapeTrims) // 新的trim抓取端点
		api.POST("/scrape_all", vehicleHandler.ScrapeAllVehicles) // 新增：抓取官网车辆清单
	}

	// 系统路由
	router.GET("/health", vehicleHandler.HealthCheck)

	// 静态文件服务 (用于测试web页面)
	router.Static("/web", "./web")
	router.StaticFile("/", "./web/index.html")

	return router
}

// CORSMiddleware CORS中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
        // 为了兼容前端本地开发，允许所有来源但不携带凭证
        c.Header("Access-Control-Allow-Origin", "*")
        // 当允许所有来源时，不应设置 Allow-Credentials 为 true
		c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
